// pages/Sound/Sound.js
import * as echarts from '../../ec-canvas/echarts';

const FS_deviceid = "D5:BB:FF:22:11:94"
const AR_deviceid = "11:FF:FF:22:11:94"

const serviceid = "E093F3B5-00A3-A9E5-9ECA-40016E0EDC24"
const fs_write_charaid = "E093F3B5-00A3-A9E5-9ECA-40026E0EDC24"

const ar_read_notifyid = "E093F3B6-00A3-A9E5-9ECA-40026E0EDC24"
const ar_write_charaid = "E093F3B7-00A3-A9E5-9ECA-40036E0EDC24"

let temp_chart = null;
let light_chart = null;
let noise_chart = null;
let gyro_chart = null;

var temp_option = {
  title: {
    text: '温度(℃)',
    left: 'center'
  },
  // legend: {
  //   data: ['温度'],
  //   bottom: 0,
  //   left: 'center',
  //   // backgroundColor: 'red',
  //   z: 100
  // },
  grid: {
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    show: false
  },
  yAxis: {
    x: 'center',
    type: 'value',
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    }
  },
  series: [{
    name: "温度",
    type: 'line',
    color: 'red',
    smooth: true,
    data: []
  }]
};

var light_option = {
  title: {
    text: '亮度（lux）',
    left: 'center'
  },
  // legend: {
  //   data: [''],
  //   bottom: 0,
  //   left: 'center',
  //   // backgroundColor: 'red',
  //   z: 100
  // },
  grid: {
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    show: false
  },
  yAxis: {
    x: 'center',
    type: 'value',
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    }
  },
  series: [{
    name: "亮度",
    type: 'line',
    color: 'yellow',
    smooth: true,
    data: []
  }]
};

var noise_option = {
  title: {
    text: '噪音(dB)',
    left: 'center'
  },
  // legend: {
  //   data: [''],
  //   bottom: 0,
  //   left: 'center',
  //   // backgroundColor: 'red',
  //   z: 100
  // },
  grid: {
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    show: false
  },
  yAxis: {
    x: 'center',
    type: 'value',
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    }
  },
  series: [{
    name: "噪音",
    type: 'line',
    color: 'black',
    smooth: true,
    data: []
  }]
};

var gyro_option = {
  title: {
    text: '速度(rpm)',
    left: 'center'
  },
  // legend: {
  //   data: [''],
  //   bottom: 0,
  //   left: 'center',
  //   // backgroundColor: 'red',
  //   z: 100
  // },
  grid: {
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    show: false
  },
  yAxis: {
    x: 'center',
    type: 'value',
    splitLine: {
      lineStyle: {
        type: 'dashed'
      }
    }
  },
  series: [{
    name: "速度",
    type: 'line',
    color: 'green',
    smooth: true,
    data: []
  }]
};

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      lazyLoad: true
    },
    loading_percent : 0,
    loading_status : false,
    state_show: '初始化中...',
    step : 0,
    rounds_value: "",
    aspeed_value: "",
    temp_pkg_counts: "",
    light_pkg_counts: "",
    noise_pkg_counts: "",
    action_pkg_counts: "",

    status_massage: "",
    
  },

  showChart(){
    this.ectemp.init((canvas, width, height, dpr) => {
      temp_chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      temp_chart.setOption(temp_option);
      return temp_chart;
    });
    this.eclight.init((canvas, width, height, dpr) => {
      light_chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      light_chart.setOption(light_option);
      return light_chart;
    });
    this.ecnoise.init((canvas, width, height, dpr) => {
      noise_chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      noise_chart.setOption(noise_option);
      return noise_chart;
    });
    this.ecgyro.init((canvas, width, height, dpr) => {
      gyro_chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      gyro_chart.setOption(gyro_option);
      return gyro_chart;
    });

  },

  pushData(option,dat,index,raido,offset) {
    
    for(let i = 0;i<18;i++){
      if(option == gyro_option & dat[i+2] == 0)
      {
        offset = 0
      }
      if(option == temp_option & dat[i+2] == 0)
      {
        offset = 0
      }
      option.series[0].data.push(dat[i+2]*raido+offset)
      option.xAxis.data.push(i + index * 18)
    }
  },

  cleanData(){
    this.setData({
      status_massage : ''
    })
    temp_option.series[0].data = []
    temp_option.xAxis.data = []
    light_option.series[0].data = []
    light_option.xAxis.data = []
    noise_option.series[0].data = []
    noise_option.xAxis.data = []
    gyro_option.series[0].data = []
    gyro_option.xAxis.data = []
    temp_chart.setOption(temp_option);
    light_chart.setOption(light_option);
    noise_chart.setOption(noise_option);
    gyro_chart.setOption(gyro_option);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取组件
    this.ectemp = this.selectComponent('#temp-line');
    this.eclight = this.selectComponent('#light-line');
    this.ecnoise = this.selectComponent('#noise-line');
    this.ecgyro = this.selectComponent('#gyro-line');
    this.showChart();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.openBluetoothAdapter()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.stopBluetoothDevicesDiscovery()
    wx.closeBluetoothAdapter({
      success: (res) => {
        console.log('closeBluetoothAdapter success', res)
      },
    })

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.stopBluetoothDevicesDiscovery()
    wx.closeBluetoothAdapter({
      success: (res) => {
        console.log('closeBluetoothAdapter success', res)
      },
    })

  },

   // 开始扫描，打开蓝牙适配器
   openBluetoothAdapter() {
    this.setData({
      state_show: "开始扫描",
      loading_percent : 1,
    })
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },

  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },

  // 开始搜索设备
  startBluetoothDevicesDiscovery() {
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },

  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },

  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        if(device.deviceId == FS_deviceid && this.foundFS != true){
          console.log('found 奖励器 ',device)
          this.setData({
            state_show: "搜索到奖励器",
            loading_percent : 7,
          })
          this.foundFS = true
          this.createFSConnection()
        }
        if(device.deviceId == AR_deviceid  && this.foundAR != true){
          console.log('found 监测器 ',device)
          this.setData({
            state_show: "搜索到监测器",
            loading_percent : 10,
          })
          this.foundAR = true
          this.createARConnection()
        }
        if(this.foundFS == true && this.foundFS == true){
          this.stopBluetoothDevicesDiscovery()
        }
      })

    })
  },

  createARConnection() {
    wx.createBLEConnection({
      deviceId: AR_deviceid,
      success: (res) => {
        console.log('create AR connection success ',res)
        this.setData({
          state_show: "连接检测器成功",
          loading_percent : 13,

        })
        this.getBLEDeviceServices(AR_deviceid)
      },
      fail: (res) => {
        console.log('createBLEConnection fail ',res)
        createARConnection()
      }
    })
  },

  createFSConnection() {
    wx.createBLEConnection({
      deviceId: FS_deviceid,
      success: (res) => {
        console.log('createBLEConnection success ',res)
        this.setData({
          state_show: "连接奖励器成功",
          loading_percent : 15,
        })
        this.getBLEDeviceServices(FS_deviceid)
      },
      fail: (res) => {
        console.log('createBLEConnection fail ',res)
        createFSConnection()
      }
    })
  },

  getBLEDeviceServices(deviceid) {
    wx.getBLEDeviceServices({
      deviceId :deviceid,
      success: (res) => {
        console.log(res.services.length)
        for (let i = 0; i < res.services.length; i++) {
          console.log(res.services[i].uuid)
          if(res.services[i].uuid== serviceid)
          {
            this.getBLEDeviceCharacteristics(deviceid, res.services[i].uuid)
            return
          }
        }
      }
    })
  },

  getBLEDeviceCharacteristics(deviceid, serviceid) {
    wx.getBLEDeviceCharacteristics({
      deviceId :deviceid,
      serviceId:serviceid,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (deviceid == AR_deviceid && item.uuid == ar_read_notifyid){
            console.log('notify ar charactoristic value success')
            wx.notifyBLECharacteristicValueChange({
              deviceId :deviceid,
              serviceId :serviceid,
              characteristicId: item.uuid,
              state: true,
            })
            this.setData({
              state_show: "设备注册成功",
              loading_percent : 18,
              step : 5
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((res) => {
      console.log("onBLECharacteristicValueChange",res)
      this.processARprotobuf(res.value)
    })
  },

  writeBLECharacteristicValue(dev,charid,buf) {
    wx.writeBLECharacteristicValue({
      deviceId: dev,
      serviceId: serviceid,
      characteristicId: charid,
      value: buf,
      success: (res) =>{
        console.log('writeBLECharacteristicValue', res)
      },
      fail: (res) => {
        console.log('writeBLECharacteristicValue', res)
        if (res.errCode === 10006) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('writeBLECharacteristicValue', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },

  setFSopen(num){
    wx.showToast({
      title: '设置'+num+"打开成功",
      icon: 'success',
      duration: 1000
    })
    let buffer = new ArrayBuffer(2)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0xff)
    dataView.setUint8(1, 0x01 << (num - 1))
    console.log("set data",buffer)
    this.writeBLECharacteristicValue(FS_deviceid,fs_write_charaid,buffer)
  },

  processARprotobuf(res){
    
    let data = new Uint8Array(res)
    switch(data[0]){
      case 0x80 :
        if(data[2] == 0x11)
          this.setData({
            send_recv_flag : 2
          })
      break
      case 0x81:
        if(data[2] == 0x11)
        this.setData({
          send_recv_flag : 2
        })
      break
      case 0x82:
        this.setData({
          send_recv_flag : 2
        })
      break
      case 0x10:
        this.aspeed = data[4]-127
        if(this.aspeed < 0)
          this.aspeed = -this.aspeed
        this.setData({
          send_recv_flag : 2,
          rounds_value: (data[2] << 8 | data[3]),
          aspeed_value: this.aspeed
        })
        if(this.data.rounds_value != 0){
          this.message = "昨天晚上，小果冻奔跑了"+this.data.rounds_value + "圈"
          if(this.data.aspeed_value > 10){
            this.message += "，最快速度达到"+this.data.aspeed_value+"rpm"+",太厉害了！！"
          }else{
            this.message += "，最快速度只有"+this.data.aspeed_value+"rpm"+",还需努力呀！！"
          }
        }else{
          this.message = "昨天晚上，小果冻偷懒了，一圈都没跑..."
        }
        this.setData({
          status_massage : this.message
        })
        this.sendcmd = false
        
      break
      
      case 0x11:
        this.temp_pkg_counts = (data[2] << 8 | data[3])
        this.temp_counts= 0
      break
      
      case 0x12:
        this.light_pkg_counts = (data[2] << 8 | data[3])
        this.light_counts= 0
      break

      case 0x13:
        this.noise_pkg_counts = (data[2] << 8 | data[3])
        this.noise_counts= 0
      break

      case 0x14:
        this.action_pkg_counts = (data[2] << 8 | data[3])
        this.action_counts= 0

      break

      case 0x01:
        if(this.temp_pkg_counts > 0){
          this.temp_pkg_counts--
          this.pushData(temp_option,data,this.temp_counts++,0.1,10)
          this.getTempDataCtrl(this.temp_counts+1)
        }else{
          temp_chart.setOption(temp_option)
          this.setData({
            state_show: "获取亮度数据",
            loading_percent : 50
          })
          this.getLightDataCtrl(1)
        }
      break
      case 0x02:
        if(this.light_pkg_counts > 0){
          this.light_pkg_counts--
          this.pushData(light_option,data,this.light_counts++,10,0)
          this.getLightDataCtrl(this.light_counts+1)
        }else{
          this.setData({
            state_show: "获取噪声数据",
            loading_percent : 70
          })
          light_chart.setOption(light_option)
          this.getNoiseDataCtrl(1)
        }
      break
      case 0x03:
        if(this.noise_pkg_counts > 0){ 
          this.noise_pkg_counts--
          this.pushData(noise_option,data,this.noise_counts++,0.25,30.0)
          this.getNoiseDataCtrl(this.noise_counts+1)
        }else{
          this.setData({
            state_show: "获取速度数据",
            loading_percent : 90
          })
          noise_chart.setOption(noise_option)
          this.getActionDataCtrl(1)
        }
      break
      case 0x04:
        if(this.action_pkg_counts > 0){
          this.action_pkg_counts--
          this.pushData(gyro_option,data,this.action_counts++,1,-127)
          this.getActionDataCtrl(this.action_counts+1)
        }else{
          gyro_chart.setOption(gyro_option)
          this.setData({
            state_show: "获取数据成功",
            loading_percent : 100,
            loading_status : true
          })
          wx.showToast({
            title: "获取数据成功",
            icon: 'success',
            duration: 2500
          })
        }
      break
    }
  },

  getRoundCtrl(){
    let buffer = new ArrayBuffer(2)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x10)
    dataView.setUint8(1, 0x00)
    console.log("getRoundCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)
  },

  getTempPkgsCounstsCtrl(){

    let buffer = new ArrayBuffer(2)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x11)
    dataView.setUint8(1, 0x00)
    console.log("getTempPkgsCounstsCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)

  },

  getLightPkgsCounstsCtrl(){

    let buffer = new ArrayBuffer(2)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x12)
    dataView.setUint8(1, 0x00)
    console.log("getLightPkgsCounstsCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)

  },

  getNoisePkgsCounstsCtrl(){

    let buffer = new ArrayBuffer(2)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x13)
    dataView.setUint8(1, 0x00)
    console.log("getNoisePkgsCounstsCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)

  },

  getActionPkgsCounstsCtrl(){

    let buffer = new ArrayBuffer(2)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x14)
    dataView.setUint8(1, 0x00)
    console.log("getActionPkgsCounstsCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)

  },

  getTempDataCtrl(index){

    let buffer = new ArrayBuffer(4)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x01)
    dataView.setUint8(1, 0x02)
    dataView.setUint8(2, index >> 8 & 0xff)
    dataView.setUint8(3, index & 0xff)
    console.log("getTempDatatsCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)

  },

  getLightDataCtrl(index){

    let buffer = new ArrayBuffer(4)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x02)
    dataView.setUint8(1, 0x02)
    dataView.setUint8(2, index >> 8 & 0xff)
    dataView.setUint8(3, index & 0xff)
    console.log("getLightDataCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)

  },

  getNoiseDataCtrl(index){

    let buffer = new ArrayBuffer(4)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x03)
    dataView.setUint8(1, 0x02)
    dataView.setUint8(2, index >> 8 & 0xff)
    dataView.setUint8(3, index & 0xff)
    console.log("getNoiseDataCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)

  },

  getActionDataCtrl(index){

    let buffer = new ArrayBuffer(4)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0x04)
    dataView.setUint8(1, 0x02)
    dataView.setUint8(2, index >> 8 & 0xff)
    dataView.setUint8(3, index & 0xff)
    console.log("getActionDataCtrl",buffer)
    this.writeBLECharacteristicValue(AR_deviceid,ar_write_charaid,buffer)

  },

  autoAward()
  {
    let award_num = 0
    if(this.data.rounds_value > 300)
      award_num |= 0x01
    if(this.data.rounds_value > 700)
      award_num |= 0x02
    if(this.data.rounds_value > 1000)
      award_num |= 0x04
    if(this.data.aspeed_value > 50)
      award_num |= 0x08
    if(this.data.aspeed_value > 100)
      award_num |= 0x10

    if(award_num == 0){
      wx.showToast({
        title: "想吃虫？跑步去",
        icon: 'error',
        duration: 1500
      })
    }
    else if(award_num > 0){
      wx.showToast({
        title: "鼓励一下！",
        icon: 'success',
        duration: 1500
      })
    }

    let buffer = new ArrayBuffer(2)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, 0xff)
    dataView.setUint8(1, award_num)
    console.log("autoAward",buffer)
    this.writeBLECharacteristicValue(FS_deviceid,fs_write_charaid,buffer)

  },

  getData(){
    
    this.cleanData()

    this.setData({
      state_show: "获取转动圈数",
      loading_percent : 20,
    })
    this.getRoundCtrl()

    this.setData({
      state_show: "获取温度包数",
      loading_percent : 22,
    })
    this.getTempPkgsCounstsCtrl()

    this.setData({
      state_show: "获取亮度包数",
      loading_percent : 24,
    })
    this.getLightPkgsCounstsCtrl()

    this.setData({
      state_show: "获取噪音包数",
      loading_percent : 26,
    })
    this.getNoisePkgsCounstsCtrl()

    this.setData({
      state_show: "获取运动包数",
      loading_percent : 28,
    })
    this.getActionPkgsCounstsCtrl()
    this.setData({
      state_show: "获取温度数据",
      loading_percent : 30,
    })
    this.getTempDataCtrl(1)


  },

})